package com.njd.test.autocreatedentity;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import com.jfinal.core.JFinal;

/***
 * 自动生成带setter与getter方法的Model
 * 
 * @author Johnson
 *
 */
public class AutoCreatedModelFile {

	public AutoCreatedModelFile(String tableName, Map<String, String> property,
			String packageName) throws IOException {
		// -----------------------拼装文件夹名
		String[] pn = packageName.split("\\.");
		StringBuffer file = new StringBuffer();
		String dir = JFinal.me().getServletContext().getRealPath("/");
		file.append(dir.substring(0, dir.length() - 7) + "src");
		for (String p : pn) {
			file.append("/");
			file.append(p);
		}
		System.out.println(file.toString());
		// -------------------------------------
		// ---------------------创建文件
		String f = createdFile(file.toString() + "/",
				FileNameManager.upFirstName(tableName) + ".java");

		FileWriter fileWriter = new FileWriter(f);
		fileWriter.write(getText(tableName, property, packageName));
		fileWriter.flush();
		fileWriter.close();
	}

	/***
	 * 创建文本内容
	 * 
	 * @param tableName
	 * @param property
	 * @return
	 */
	private String getText(String tableName, Map<String, String> property,
			String packageName) {
		String classname = FileNameManager.upFirstName(tableName);

		// 参数对组
		String para = entrypara(property);
		String ln = "\r\n";
		String tab = "\t\t";
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packageName + ";" + ln + ln
				+ "import com.jfinal.plugin.activerecord.Model;" + ln
				+ "import com.jfinal.plugin.activerecord.TableMapping;" + ln
				+ "import com.jfinal.plugin.activerecord.Db;" + ln
				+ "import java.util.HashMap;" + ln + "import java.util.List;"
				+ ln + "import java.util.Map;" + ln + inputPackage(property)
				+ "/***" + ln + " * 自动生成的Model" + ln
				+ " * @author Johnson Zhang" + ln + " *" + ln + " */" + ln
				+ "@SuppressWarnings(\"serial\")" + ln + "public class "
				+ classname + " extends Model<" + classname + ">{" + ln);
		// 空构造与有参构造
		sb.append(classTextStringLine(new String[] {
				"//--------------setter和getter---------------",
				entryBean(classname, property),
				"//-------------------------------------------",
				"/***",
				"*数据库操作实体",
				"*/",
				"public static final " + classname + " dao=new " + classname
						+ "();",
				"/**",
				"* 表名",
				"*/",
				"public static final String tableName=\"" + tableName + "\";",
				"/**",
				"* 表主键",
				"*/",
				"public static final String primaryKey[]=TableMapping.me().getTable(dao.getClass()).getPrimaryKey();",
				"/***",
				"* 空构造",
				"*/",
				"public " + classname + "(){}",
				"/***",
				"* 有参构造",
				"*/",
				"public " + classname + "(",
				para,
				"){",
				"setData(" + ln + tab + entryparas(property) + ln + tab + ");",
				"}",
				"/***",
				"*数据批量设置",
				"*/",
				"public " + classname + " setData(" + ln + "\t\t" + para + "){",
				setString(property),
				"return this;",
				"}",
				"/***",
				"* 按ID逆序查询全部数据",
				"* @param pageNumber 页码",
				"* @param pageSize 每页记录数",
				"* @return",
				"* @throws Exception ",
				"*/",
				"public Map<String,Object> paginate(int pageNumber, int pageSize,String para,Object value) throws Exception {",
				classTextStringLine(new String[] {
						tab + "Object[] o=new Object[]{};",
						tab + "StringBuffer sb=new StringBuffer();",
						tab + "sb.append(\"from \"+tableName);",
						tab + "if(value!=null&&value!=null&&value!=\"\")",
						tab + "{",
						tab + tab + "o= new Object[]{value};",
						tab + tab + "sb.append(\" where \"+para+\"=?\");",
						tab + "}",
						tab
								+ "sb.append(\" order by \"+primaryKey[0]+\" DESC\");",
						// ----------------------",
						// 数据封装",
						tab
								+ "Long num=Db.queryLong(\"select count(1) \"+sb.toString(),o);",
						tab
								+ "List<?> data = paginate(pageNumber, pageSize, \"select *\", sb.toString(),o).getList();",
						tab
								+ "Map<String,Object> m=new HashMap<String, Object>();",
						tab + tab + "m.put(\"data\", data);",
						tab + tab + "m.put(\"num\", num);", tab + "return m;",
						"}" })

		}));
		sb.append(ln + "}");
		return sb.toString();
	}

	/***
	 * 创建文件
	 * 
	 * @param path
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	private String createdFile(String path, String filename) throws IOException {
		// 判断文件夹是否存在
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		System.out.println(dir.getPath());
		// 判断文件是否存在
		File f = new File(dir.getPath() + "/" + filename);
		if (!f.exists()) {
			f.createNewFile();
		} else {
			f.delete();
			f.createNewFile();
		}

		return f.getPath();
	}

	/***
	 * 文本格式化
	 * 
	 * @param s
	 * @return
	 */
	private String classTextStringLine(String[] s) {
		StringBuffer sb = new StringBuffer();
		for (String k : s) {
			sb.append("\t\t" + k + "\r\n");
		}
		return sb.toString();
	}

	/***
	 * 构建类似Bean
	 * 
	 * @param classname
	 * @param property
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String entryBean(String classname, Map<String, String> property) {
		StringBuffer sb = new StringBuffer();
		sb.append("\r\n");
		/*
		 * //构建引用 Iterator i=property.entrySet().iterator();
		 * while(i.hasNext()){//只遍历一次,速度快 Map.Entry e=(Map.Entry)i.next();
		 * sb.append("\t\tpublic "+e.getValue().toString()+" " +
		 * FileNameManager.CamelCase(e.getKey().toString().split("_"))+";" +
		 * "\r\n"); }
		 */
		// 构建setter和getter
		Iterator k = property.entrySet().iterator();
		while (k.hasNext()) {// 只遍历一次,速度快
			Map.Entry e = (Map.Entry) k.next();
			String propetyname = FileNameManager.CamelCase(e.getKey()
					.toString().split("_"));
			// setter
			sb.append("\t\tpublic "
					+ classname
					+ " set"
					+ FileNameManager.upFirstNameNoLowerCase(propetyname)
					+ "("
					+ e.getValue()
					+ " "
					+ propetyname
					+ "){"
					+ "\r\n"
					+ classTextStringLine(new String[] {
							// tab"\t\t" +"this." +propetyname+"="+propetyname+
							// ";",
							"\t\t" + "set(\"" + e.getKey() + "\","
									+ propetyname + ");",
							"\t\t" + "return this;", "\t\t" + "}" }) + "\r\n");
			sb.append("\t\tpublic "
					+ e.getValue()
					+ " get"
					+ FileNameManager.upFirstNameNoLowerCase(propetyname)
					+ "(){"
					+ "\r\n"
					+ classTextStringLine(new String[] {
							"\t\t" + "return get(\"" + e.getKey() + "\");",
							"\t\t" + "}" }) + "\r\n");
		}
		return sb.toString();
	}

	/***
	 * 构建传参的字符串
	 * 
	 * @param property
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String entrypara(Map<String, String> property) {
		StringBuffer sb = new StringBuffer();
		// 构建引用
		sb.append("\r\n");
		Iterator i = property.entrySet().iterator();
		while (i.hasNext()) {// 只遍历一次,速度快
			Map.Entry e = (Map.Entry) i.next();
			String propetyname = FileNameManager.CamelCase(e.getKey()
					.toString().split("_"));
			sb.append("\t\t\t\t" + e.getValue().toString() + " " + propetyname
					+ "," + "\r\n");
		}
		return sb.substring(4, sb.lastIndexOf(","));
	}

	@SuppressWarnings("rawtypes")
	private String entryparas(Map<String, String> property) {
		StringBuffer sb = new StringBuffer();
		// 构建引用
		sb.append("\r\n");
		Iterator i = property.entrySet().iterator();
		while (i.hasNext()) {// 只遍历一次,速度快
			Map.Entry e = (Map.Entry) i.next();
			String propetyname = FileNameManager.CamelCase(e.getKey()
					.toString().split("_"));
			sb.append("\t\t\t\t" + propetyname + "," + "\r\n");
		}
		return sb.substring(4, sb.lastIndexOf(","));
	}

	/***
	 * 批量set
	 * 
	 * @param property
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String setString(Map<String, String> property) {
		StringBuffer sb = new StringBuffer();
		// 构建引用
		sb.append("\r\n");
		Iterator i = property.entrySet().iterator();
		while (i.hasNext()) {// 只遍历一次,速度快
			Map.Entry e = (Map.Entry) i.next();
			String propetyname = FileNameManager.CamelCase(e.getKey()
					.toString().split("_"));
			sb.append("\t\t\t\tset(\"" + e.getKey().toString() + "\","
					+ propetyname + ");\r\n");
		}
		return sb.substring(4, sb.length() - 2);
	}

	@SuppressWarnings("rawtypes")
	private String inputPackage(Map<String, String> property) {
		StringBuffer sb = new StringBuffer();
		// 构建引用
		sb.append("\r\n");
		Iterator i = property.entrySet().iterator();
		while (i.hasNext()) {// 只遍历一次,速度快
			Map.Entry e = (Map.Entry) i.next();
			String type = e.getValue().toString();
			String packages = null;
			if (type.equals("BigInteger")) {
				packages = "import java.math.BigIntege;\r\nr";
			} else if (type.equals("BigDecimal")) {
				packages = "import java.math.BigDecimal;\r\n";
			} else if (type.equals("Date")) {
				packages = "import java.util.Date;\r\n";
			} else if (type.equals("Timestamp")) {
				packages = "import java.sql.Timestamp;\r\n";
			} else if (type.equals("Time")) {
				packages = "import java.sql.Time;\r\n";
			} else {
				packages = "";
			}
			sb.append(packages);
		}
		return sb.toString();
	}
}